package com.contactsconverter.activity;

import java.util.Set;

import org.apache.http.client.entity.UrlEncodedFormEntity;

import com.contactsconverter.model.CTContactModel;
import com.contactsconverter.service.CTSynchroniseService;
import com.contactsconverter.utils.CTUtils;
import com.contactsconverter.R;
import com.difsonapps.contacttranslator.dto.ContactDTO;
import com.difsonapps.contacttranslator.dto.UserDTO;

import android.support.v7.app.ActionBarActivity;
import android.support.v4.app.Fragment;
import android.support.v4.app.NavUtils;
import android.accounts.Account;
import android.accounts.AccountManager;
import android.annotation.TargetApi;
import android.app.NotificationManager;
import android.content.Context;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.AsyncTask.Status;
import android.os.Build;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.TextView;
import android.widget.Toast;

public class CTSynchroniserActivity extends ActionBarActivity {

	private NotificationManager mNotificationManager;
	private static String mAccountName = "";
	public static CTSynchroniseService cTSynchroniseService;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_ctsynchroniser);
		if (savedInstanceState == null) {
			getSupportFragmentManager().beginTransaction()
			.add(R.id.container, new PlaceholderFragment()).commit();
		}

		mNotificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);

		mNotificationManager.cancel(CTUtils.synchonisation_save);
		Account[] accounts = AccountManager.get(this).getAccountsByType(
				CTUtils.ACCOUNT_TYPE);

		if (accounts.length == 0) {

			Intent intent = new Intent(this, CTLoginActivity.class);
			intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP
					| Intent.FLAG_ACTIVITY_SINGLE_TOP);
			startActivityForResult(intent, 1001);
		} else {
			mAccountName = accounts[0].name;
		}

	}

	private void initLayout() {

		View rootView = getLayoutInflater().inflate(
				R.layout.fragment_ctsynchroniser, null);
		// TextView textView = (TextView)
		// rootView.findViewById(R.id.ct_synchronisation_header);
		// if(textView == null)
		// Log.e("IDIOT",
		// String.format(getString(R.string.ct_synchronisation_msg),
		// CTContactsActivity.contactModelList.size(),
		// CTContactsActivity.contactModelSimList.size()));
		// textView.setText("Taponno");

		// rootView.findViewById(R.id.ct_button_synchronise_save).setOnClickListener(this);
		// rootView.findViewById(R.id.ct_button_synchronise_upload).setOnClickListener(this);
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.ctsynchroniser, menu);
		return false;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		// Handle action bar item clicks here. The action bar will
		// automatically handle clicks on the Home/Up button, so long
		// as you specify a parent activity in AndroidManifest.xml.
		int id = item.getItemId();
		if (id == R.id.action_settings) {
			return true;
		}
		if (id == android.R.id.home) {

			Intent upIntent = NavUtils.getParentActivityIntent(this);
			upIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP
					| Intent.FLAG_ACTIVITY_SINGLE_TOP);
			NavUtils.navigateUpTo(this, upIntent);
			return true;
		}
		return super.onOptionsItemSelected(item);
	}

	/**
	 * A placeholder fragment containing a simple view.
	 */
	public static class PlaceholderFragment extends Fragment {

		public PlaceholderFragment() {
		}

		@Override
		public View onCreateView(LayoutInflater inflater, ViewGroup container,
				Bundle savedInstanceState) {
			View rootView = inflater.inflate(R.layout.fragment_ctsynchroniser,
					container, false);
			try{
				TextView textView = (TextView) rootView
						.findViewById(R.id.ct_synchronisation_header);

				textView.setText(String.format(
						getString(R.string.ct_synchronisation_msg),
						CTContactsActivity.contactModelList.size()));

				rootView.findViewById(R.id.ct_button_synchronise_save)
				.setOnClickListener(new OnClickListener() {

					@Override
					public void onClick(View v) {
						onClick1(v);

					}
				});
				rootView.findViewById(R.id.ct_button_synchronise_upload)
				.setOnClickListener(new OnClickListener() {

					@Override
					public void onClick(View v) {
						onClick1(v);

					}
				});
			}catch (Exception e) {
				Log.e(CTSynchroniserActivity.class.getName(), e.getMessage()+"");
				getActivity().finish();
				startActivity(new Intent(getActivity(), CTMainActivity.class));
				
			}

			return rootView;
		}

		@TargetApi(Build.VERSION_CODES.HONEYCOMB)
		public void onClick1(View view) {
			switch (view.getId()) {

			case R.id.ct_button_synchronise_save:

				// Toast.makeText(getActivity(),
				// "ct_button_synchronise_save"+mAccountName,
				// Toast.LENGTH_LONG).show();
				// new CTSynchroniseService().execute(getActivity());
				if(cTSynchroniseService == null){
					cTSynchroniseService =  new CTSynchroniseService();

				}
				Log.e("cTSynchroniseService.getStatus()", cTSynchroniseService.getStatus()+"");
				if(cTSynchroniseService.getStatus() == Status.PENDING || cTSynchroniseService.getStatus() == Status.FINISHED)
					if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {

						cTSynchroniseService.executeOnExecutor(
								AsyncTask.THREAD_POOL_EXECUTOR, getActivity());
					} else {
						cTSynchroniseService.execute(getActivity());
					}

				break;
			case R.id.ct_button_synchronise_upload:
				Toast.makeText(getActivity(),
						"Cette fonction est en cours de developpement.",
						Toast.LENGTH_LONG).show();
				break;
			default:
				break;
			}

		}



	}

	@Override
	protected void onActivityResult(int req, int rep, Intent data) {

		int LOGINSUCCESS =  CTUtils.stringToInt(CTUtils.getPreference(CTUtils.LOGINSUCCESS, this));

		Log.e("rep", rep+" LOGINSUCCESS "+ LOGINSUCCESS);
		if(LOGINSUCCESS == 1024)
		{
			Log.e("ICI", rep+" RESULT_OK "+ RESULT_OK);
			initLayout();
		}else{
			Log.e("LABAS", rep+" RESULT_OK "+ RESULT_OK);
			finish();
		}
		super.onActivityResult(rep, req, data);
	}

	@Override
	public void onBackPressed() {
		// finish() is called in super: we only override this method to be able to override the transition
		super.onBackPressed();
		overridePendingTransition(R.anim.activity_back_in, R.anim.activity_back_out);
	}
}
